package com.ywz.project.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ywz.common.ResultResp;
import com.ywz.common.StringUtils;
import com.ywz.project.base.system.entity.TDepartment;
import com.ywz.project.base.system.entity.TSysRole;
import com.ywz.project.base.system.entity.TSysUser;
import com.ywz.project.base.system.entity.TSysUserRole;
import com.ywz.project.base.system.service.TDepartmentService;
import com.ywz.project.base.system.service.TSysRoleService;
import com.ywz.project.base.system.service.TSysUserRoleService;
import com.ywz.project.base.system.service.TSysUserService;
import com.ywz.project.system.dto.req.EditUserReq;
import com.ywz.project.system.dto.req.UserPageReq;
import com.ywz.project.system.dto.resp.UserPageResp;
import com.ywz.project.system.service.SysUserApiService;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysUserApiServiceImpl implements SysUserApiService {
    @Resource
    private TSysUserService tSysUserService;
    @Resource
    private TSysRoleService tSysRoleService;
    @Resource
    private TSysUserRoleService tSysUserRoleService;
    @Resource
    private TDepartmentService tDepartmentService;

    @Override
    public ResultResp getUserPage(UserPageReq req) {
        // 查询条件：账号、姓名、部门
        LambdaQueryWrapper<TSysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TSysUser::getIsDeleted, 0);
        if (!StringUtils.isEmpty(req.getName()))
            queryWrapper.like(TSysUser::getName, req.getName());
        if (!StringUtils.isEmpty(req.getAccount()))
            queryWrapper.like(TSysUser::getUsername, req.getAccount());
        if (!StringUtils.isNull(req.getDeptId()))
            queryWrapper.eq(TSysUser::getDeptId, req.getDeptId());
        // 查询用户分页
        Page<TSysUser> page = tSysUserService.page(new Page<>(req.getPageNum(), req.getPageSize()), queryWrapper);
        // 获取部门列表
        LambdaQueryWrapper<TDepartment> departmentWrapper = new LambdaQueryWrapper<>();
        departmentWrapper.eq(TDepartment::getIsDeleted, 0);
        List<TDepartment> departmentList = tDepartmentService.list(departmentWrapper);
        // 获取角色列表
        LambdaQueryWrapper<TSysRole> roleWrapper = new LambdaQueryWrapper<>();
        roleWrapper.eq(TSysRole::getIsDeleted, 0);
        List<TSysRole> roleList = tSysRoleService.list(roleWrapper);
        // 获取用户角色列表
        List<TSysUserRole> userRoleList = tSysUserRoleService.list();
        // 组装响应数据
        Page<UserPageResp> respPage = new Page<>();
        respPage.setCurrent(page.getCurrent());
        respPage.setSize(page.getSize());
        respPage.setTotal(page.getTotal());
        List<UserPageResp> collect = page.getRecords().stream().map(user -> {
            UserPageResp userPageResp = new UserPageResp();
            BeanUtils.copyProperties(user, userPageResp);
            // 设置部门名称
            if (!StringUtils.isNull(user.getDeptId())) {
                TDepartment department = departmentList.stream().filter(dept -> dept.getId().equals(user.getDeptId())).findFirst().orElse(new TDepartment());
                userPageResp.setDeptName(department.getDeptName());
            }
            // 获取用户角色列表
            List<Integer> roleIds = userRoleList.stream().filter(userRole -> userRole.getUserId().equals(user.getId())).map(TSysUserRole::getRoleId).collect(Collectors.toList());
            if (!roleIds.isEmpty()) {
                // 获取角色列表
                List<TSysRole> roleCollect = roleList.stream().filter(role -> roleIds.contains(role.getId())).collect(Collectors.toList());
                userPageResp.setRoles(roleCollect);
                userPageResp.setRoleName(roleCollect.stream().map(TSysRole::getRoleName).collect(Collectors.joining(",")));
            }
            return userPageResp;
        }).collect(Collectors.toList());
        respPage.setRecords(collect);
        return ResultResp.success(respPage);
    }

    @Override
    public ResultResp editUser(EditUserReq req) {
        // 数据校验
        if (StringUtils.isEmpties(req.getAccount(), req.getName()))
            return ResultResp.error("参数不能为空");
        if (!StringUtils.isNumberAndSeparator(req.getRoleIds()))
            return ResultResp.error("角色id格式不正确");

        // 添加、更新用户信息
        TSysUser user = new TSysUser();
        BeanUtils.copyProperties(req, user);
        user.setUsername(req.getAccount());
        if (StringUtils.isNull(req.getId())) {
            LambdaQueryWrapper<TSysUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TSysUser::getUsername, req.getAccount());
            List<TSysUser> list = tSysUserService.list(queryWrapper);
            if (!list.isEmpty())
                return ResultResp.error("用户名已存在");
            if (StringUtils.isEmpty(req.getPassword()))
                return ResultResp.error("添加时密码不能为空");
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            user.setPassword(encoder.encode(req.getPassword()));
            user.setCreateTime(LocalDateTime.now());
            tSysUserService.save(user);
        } else {
            user.setUpdateTime(LocalDateTime.now());
            user.setPassword(null);
            tSysUserService.updateById(user);
        }

        // 更新用户角色
        String[] split = req.getRoleIds().split(StringUtils.SEPARATOR);
        List<TSysUserRole> collect = Arrays.stream(split).map(roleId -> {
            TSysUserRole userRole = new TSysUserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(Integer.parseInt(roleId));
            return userRole;
        }).collect(Collectors.toList());
        tSysUserRoleService.saveBatch(collect);
        return ResultResp.success();
    }

    @Override
    public ResultResp removeUser(String ids) {
        if (StringUtils.isNumberAndSeparator(ids)) {
            String[] split = ids.split(StringUtils.SEPARATOR);
            List<Integer> userIds = Arrays.stream(split).map(Integer::parseInt).collect(Collectors.toList());
            // 删除角色关联
            LambdaUpdateWrapper<TSysUserRole> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.in(TSysUserRole::getUserId, userIds);
            tSysUserRoleService.remove(updateWrapper);
            // 删除用户
            LambdaUpdateWrapper<TSysUser> userLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            userLambdaUpdateWrapper.in(TSysUser::getId, userIds);
            userLambdaUpdateWrapper.set(TSysUser::getIsDeleted, 1);
            userLambdaUpdateWrapper.set(TSysUser::getUpdateTime, LocalDateTime.now());
            tSysUserService.update(userLambdaUpdateWrapper);
            return ResultResp.success();
        }
        return ResultResp.error("参数格式不正确");
    }
}
